package com.mszlu.union.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Service
@Slf4j
public class AuthService {

    public boolean auth(HttpServletRequest request, Authentication authentication){
        log.info("request url:{}",request.getRequestURI());
        //true代表放行 false 代表拦截
        Object principal = authentication.getPrincipal();
        if (principal == null || "anonymousUser".equals(principal)){
            //未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            MySimpleGrantedAuthority mySimpleGrantedAuthority = (MySimpleGrantedAuthority) authority;
            String path = mySimpleGrantedAuthority.getPath();
            String[] split = StringUtils.split(request.getRequestURI(), "?");
            if (split[0].equals(path)){
                return true;
            }
        }
        return false;
    }
}
